package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.common.MessageConstant;
import com.atguigu.constant.RedisConstant;
import com.atguigu.pojo.Setmeal;
import com.atguigu.service.SetmealService;
import com.atguigu.util.QiniuUtils;
import com.atguigu.vo.PageResult;
import com.atguigu.vo.QueryPageBean;
import com.atguigu.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/Setmeal")
public class SetmealController {
     @Reference
     SetmealService setmealService;
     @Autowired
     private JedisPool jedisPool;

     @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        PageResult pageResult= setmealService.findPage(queryPageBean.getCurrentPage(),
                 queryPageBean.getPageSize(),
                 queryPageBean.getQueryString());
         return pageResult;
     }
     @RequestMapping("/upload")
    public Result Upload(MultipartFile imgFile){
         try {
             String originalFilename=imgFile.getOriginalFilename();

             int lastIndexOf =originalFilename.lastIndexOf(".");
             String suffix =originalFilename.substring(lastIndexOf);
             String fileName = UUID.randomUUID().toString()+suffix;
             QiniuUtils.upload2Qiniu(imgFile.getBytes(),fileName);
             Result result=new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS,fileName);
             jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,fileName);
             return  result;
         } catch (IOException e) {
             e.printStackTrace();
         }
         return  new Result(false,MessageConstant.PIC_UPLOAD_FAIL);

     }
     @RequestMapping("/add")
    public Result add(@RequestBody Setmeal setmeal,Integer[] travelgroupIds){
         try {
             setmealService.add(setmeal,travelgroupIds);
         } catch (Exception e) {
             return new Result(false,MessageConstant.ADD_SETMEAL_FAIL);
         }
         return new Result(true,MessageConstant.ADD_SETMEAL_SUCCESS);

     }

}
